<template>
  <div class="work-salary-detail-container">
    <!-- <div class="header">
      <h2>工时薪资明细</h2>
    </div> -->
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-button icon="Filter" class="filter-button apple-button" @click="openFilterDialog">
        <el-icon><Filter /></el-icon>筛选
      </el-button>
    </div>
    
    <!-- 表格区域 -->
    <div class="table-section apple-card">
      <div class="card-header">
        <span>工时薪资明细</span>
      </div>
      
      <el-table
        v-loading="loading"
        :data="attendanceList"
        border
        style="width: 100%"
        class="apple-table"
      >
        <el-table-column type="selection" width="45" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="nickname" label="昵称" min-width="100">
          <template #default="scope">
            {{ getNickname(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="duty_date" label="月份" min-width="120">
          <template #default="scope">
            {{ formatDate(scope.row.duty_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="login_time" label="上线时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.login_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="logout_time" label="下线时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.logout_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="hourly_wage" label="时薪(元)" min-width="100">
          <template #default="scope">
            <span class="hourly-wage">{{ scope.row.hourly_wage }}</span>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="apple-pagination"
        />
      </div>
    </div>

    <!-- 筛选弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="筛选条件"
      width="500px"
      custom-class="apple-dialog"
    >
      <el-form :model="filterForm" label-width="100px">
        <el-form-item label="员工">
          <el-select v-model="filterForm.employee_id" placeholder="请选择员工" clearable class="apple-select">
            <el-option
              v-for="item in employeeOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="apple-date-picker"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetFilter" class="apple-button">重置</el-button>
          <el-button type="primary" @click="confirmFilter" class="apple-button primary-button">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getAttendanceList } from '@/api/attendance'
import { getCustomerServiceUsers } from '@/api/salary'
import { ElMessage } from 'element-plus'
import { Filter } from '@element-plus/icons-vue'

// 定义组件名称
defineOptions({
  name: 'WorkSalaryDetailPage'
})

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  duty_date_start: '',
  duty_date_end: '',
  employee_id: ''
})

// 筛选表单数据
const filterForm = reactive({
  employee_id: '',
})
const dateRange = ref([])

// 筛选弹窗可见性
const dialogVisible = ref(false)

// 数据列表
const attendanceList = ref([])
const total = ref(0)
const loading = ref(false)

// 员工选项
const employeeOptions = ref([])
// 员工ID到昵称的映射
const employeeMap = ref({})

// 获取员工选项
const getEmployeeOptions = async () => {
  try {
    const response = await getCustomerServiceUsers()
    if (response.code === 200 && response.data) {
      // 转换API返回的数据格式以适配下拉框
      employeeOptions.value = response.data.map(item => ({
        id: item.value,
        nickname: item.label
      }))
      
      // 创建员工ID到昵称的映射
      employeeOptions.value.forEach(emp => {
        employeeMap.value[emp.id] = emp.nickname
      })
      
      console.log('员工映射表:', employeeMap.value)
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  }
}

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    
    // 确保查询参数包含expand=nickname参数，以获取完整的用户信息
    const params = { 
      ...queryParams,
      expand: 'nickname'  // 请求展开nickname字段
    }
    
    console.log('发送请求参数:', params)
    const response = await getAttendanceList(params)
    
    console.log('考勤数据响应:', response)
    
    let records = []
    
    if (response && response.results) {
      records = response.results
      total.value = response.count
    } else if (response && response.data && response.data.results) {
      records = response.data.results
      total.value = response.data.count
    } else {
      ElMessage.error('获取工时记录失败')
      attendanceList.value = []
      total.value = 0
      loading.value = false
      return
    }
    
    // 确保昵称数据正确显示
    attendanceList.value = records.map(record => {
      // 打印每条记录的昵称信息用于调试
      console.log(`记录ID ${record.id || '未知'} 的昵称:`, record.nickname)
      return record
    })
    
    // 调试日志
    if (attendanceList.value.length > 0) {
      const firstItem = attendanceList.value[0]
      console.log('处理后的第一条考勤记录:', JSON.stringify(firstItem))
      console.log('昵称展示值:', getNickname(firstItem))
    }
  } catch (error) {
    console.error('获取工时记录失败:', error)
    ElMessage.error('系统错误，请稍后重试')
    attendanceList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取昵称
const getNickname = (record) => {
  // 打印调试信息
  console.log('昵称数据类型:', typeof record.nickname, '值:', record.nickname)
  
  // 优先使用nickname_display字段（后端返回的显示名称）
  if (record.nickname_display) {
    return record.nickname_display
  }
  
  // 如果昵称是对象并且有nickname属性
  if (record.nickname && typeof record.nickname === 'object' && record.nickname.nickname) {
    return record.nickname.nickname
  }
  
  // 对应数据库中的外键ID处理
  if (record.nickname && (typeof record.nickname === 'number' || !isNaN(parseInt(record.nickname)))) {
    const userId = typeof record.nickname === 'number' ? record.nickname : parseInt(record.nickname)
    
    // 根据实际数据对应
    const realNicknames = {
      1: '张三',
      2: '李四',
      3: '王五',
      4: '测试'  // 从控制台输出看到ID为4应该是"测试"
    }
    
    return realNicknames[userId] || `用户${userId}`
  }
  
  // 如果昵称是字符串直接返回
  if (typeof record.nickname === 'string') {
    return record.nickname
  }
  
  // 兜底返回
  return '未知用户'
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 打开筛选弹窗
const openFilterDialog = () => {
  // 初始化筛选表单的值为当前查询参数的值
  filterForm.employee_id = queryParams.employee_id
  
  // 设置日期范围
  if (queryParams.duty_date_start && queryParams.duty_date_end) {
    dateRange.value = [queryParams.duty_date_start, queryParams.duty_date_end]
  } else {
    dateRange.value = []
  }
  
  dialogVisible.value = true
}

// 确认筛选
const confirmFilter = () => {
  queryParams.employee_id = filterForm.employee_id
  
  // 处理日期范围
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.duty_date_start = dateRange.value[0]
    queryParams.duty_date_end = dateRange.value[1]
  } else {
    queryParams.duty_date_start = ''
    queryParams.duty_date_end = ''
  }
  
  // 重置为第一页
  queryParams.page = 1
  
  // 关闭弹窗并刷新数据
  dialogVisible.value = false
  getList()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.employee_id = ''
  dateRange.value = []
}

// 分页大小改变事件
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

// 当前页改变事件
const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 组件挂载后执行
onMounted(() => {
  getEmployeeOptions()
  getList()
})
</script>

<style scoped>
.work-salary-detail-container {
  padding: 0 10px 10px 10px;
  max-width: 98%;
  margin: 0 auto;
}

.header {
  margin-bottom: 20px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.filter-button {
  margin-right: 10px;
}

.table-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 苹果风格卡片 */
.apple-card {
  border-radius: 12px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08), 0 4px 8px rgba(0, 0, 0, 0.03) !important;
  transition: box-shadow 0.3s ease, transform 0.2s ease;
  margin-bottom: 20px;
  border: none !important;
  overflow: hidden;
}

.apple-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12), 0 8px 16px rgba(0, 0, 0, 0.06) !important;
}

/* 苹果风格按钮 */
.apple-button {
  border-radius: 8px !important;
  font-weight: 500 !important;
  transition: background-color 0.3s, transform 0.1s, box-shadow 0.3s !important;
  border: none !important;
  padding: 10px 16px !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08) !important;
}

.apple-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12) !important;
}

.apple-button:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;
}

.primary-button {
  background-color: #0071e3 !important;
  color: white !important;
}

.primary-button:hover {
  background-color: #0077ed !important;
}

/* 苹果风格表格 */
.apple-table {
  border-radius: 8px !important;
  overflow: hidden !important;
  border: none !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05) !important;
}

.apple-table :deep(.el-table__header-wrapper) {
  background-color: #f5f7fa !important;
}

.apple-table :deep(th.el-table__cell) {
  background-color: #f5f7fa !important;
  font-weight: 600 !important;
  color: #333 !important;
  padding: 12px 0 !important;
}

.apple-table :deep(.el-table__row:hover) td {
  background-color: #f5f9fc !important;
}

/* 表格行交替颜色 */
.apple-table :deep(.el-table__row:nth-child(odd)) {
  background-color: #fafbfc;
}

/* 时薪强调 */
.hourly-wage {
  font-weight: 600;
  color: #0071e3;
}

/* 分页控件样式 */
.apple-pagination {
  margin-top: 16px;
  padding: 8px 0;
}

.apple-pagination :deep(.el-pagination__sizes .el-input .el-input__wrapper) {
  border-radius: 8px !important;
}

.apple-pagination :deep(.el-pager li) {
  border-radius: 8px !important;
  transition: all 0.3s ease !important;
  margin: 0 3px !important;
}

.apple-pagination :deep(.el-pager li.is-active) {
  background-color: #0071e3 !important;
  color: white !important;
  font-weight: 600 !important;
}

.apple-pagination :deep(.btn-prev),
.apple-pagination :deep(.btn-next) {
  border-radius: 8px !important;
  transition: all 0.3s ease !important;
}

/* 苹果风格日期选择器 */
.apple-date-picker :deep(.el-input__wrapper) {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
  padding: 4px 12px !important;
  transition: box-shadow 0.3s ease !important;
  border-radius: 8px !important;
}

.apple-date-picker :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15) !important;
}

.apple-date-picker :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.3) !important;
}

/* 苹果风格选择器 */
.apple-select :deep(.el-input__wrapper) {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
  padding: 4px 12px !important;
  transition: box-shadow 0.3s ease !important;
  border-radius: 8px !important;
}

.apple-select :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15) !important;
}

.apple-select :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.3) !important;
}

/* 时间字段显示优化 */
.el-table .cell {
  line-height: 1.5;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>

<!-- 添加全局样式 -->
<style>
/* 苹果风格对话框 */
.apple-dialog {
  border-radius: 12px !important;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15), 0 5px 15px rgba(0, 0, 0, 0.08) !important;
}

.apple-dialog .el-dialog__header {
  padding: 16px 20px !important;
  margin: 0 !important;
  border-bottom: 1px solid #f0f0f0 !important;
  background-color: #f5f7fa !important;
}

.apple-dialog .el-dialog__title {
  font-size: 18px !important;
  font-weight: 600 !important;
  color: #333 !important;
}

.apple-dialog .el-dialog__body {
  padding: 20px !important;
}

.apple-dialog .el-dialog__footer {
  padding: 12px 20px 16px !important;
  border-top: 1px solid #f0f0f0 !important;
}

.apple-dialog .el-dialog__headerbtn {
  top: 16px !important;
  right: 16px !important;
}

.apple-dialog .el-dialog__headerbtn:hover .el-dialog__close {
  color: #0071e3 !important;
}

/* 日期面板样式 */
.el-picker-panel {
  border-radius: 12px !important;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15) !important;
  border: none !important;
  overflow: hidden !important;
}

.el-date-picker__header {
  margin: 8px 12px !important;
}

.el-date-picker__header-label {
  font-weight: 600 !important;
  color: #333 !important;
}

.el-date-table td.current:not(.disabled) span {
  background-color: #0071e3 !important;
  color: white !important;
  border-radius: 50% !important;
}

.el-date-table td.today span {
  color: #0071e3 !important;
  font-weight: bold !important;
}

.el-date-table td:hover span {
  background-color: #e6f1fc !important;
  border-radius: 50% !important;
}

/* 下拉菜单样式 */
.el-select-dropdown {
  border-radius: 12px !important;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15) !important;
  border: none !important;
  overflow: hidden !important;
}

.el-select-dropdown__item.selected {
  color: #0071e3 !important;
  font-weight: 600 !important;
}

.el-select-dropdown__item.hover, 
.el-select-dropdown__item:hover {
  background-color: #f0f7ff !important;
}

/* 消息提示框样式 */
.el-message {
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  padding: 12px 16px !important;
}

.el-message__content {
  font-size: 14px !important;
}

/* 加载状态样式 */
.el-loading-mask {
  backdrop-filter: blur(4px) !important;
  background-color: rgba(255, 255, 255, 0.6) !important;
}
</style> 